package com.globallogic.javatrainings.sergiiivanov.controller;

import com.globallogic.javatrainings.sergiiivanov.model.University;
import com.globallogic.javatrainings.sergiiivanov.model.UniversityFailure;
import com.globallogic.javatrainings.sergiiivanov.model.UniversityWarning;
import com.globallogic.javatrainings.sergiiivanov.view.BuildingsManagementPage;

class BuildingsMenuController extends BasicController {
    private BuildingsManagementPage page = new BuildingsManagementPage();

    private enum States {
        ADD_BUILDING, ADD_PERSON, SHOW_BUILDINGS
    };

    private int command;
    private States currentState;
    private University university;

    @Override
    BasicController initiate(University u) throws UniversityFailure {
        this.university = u;

        if (currentState == States.SHOW_BUILDINGS) {
            return showBuildings();
        }
        if (currentState == States.ADD_BUILDING) {
            return addBuilding();
        }
        currentState = States.SHOW_BUILDINGS;
        return this;
    }

    private BasicController addBuilding() {
        page.pageAddNewBuilding();
        String newBuildingName = InputController.readString();
        try {
            university.buildings.addBuilding(newBuildingName);
            return new BuildingDetailsController(university.buildings.getBuildingByIndex(university.buildings.countBuildings() - 1));
        } catch (Exception e) {
            page.error("Failed to add building",
                    e.getMessage());
        }
        currentState = States.SHOW_BUILDINGS;
        return this;
    }

    private void readCommand() {
        command = InputController.readInt();

    }

    private BasicController showBuildings() throws UniversityFailure {
        String[] buildings = university.buildings.getBuildings().toNamesList();
        page.pageBuildingsList(university.getTitle(),
                buildings);
        readCommand();
        int menuItems = 2 + buildings.length;
        int offset = 1;
        if (command >= menuItems) {
            return this;
        }
        if (command == 0) {
            return null;
        }
        if (command == (menuItems - 1)) {
            return addBuilding();
        }
        try {
            return new BuildingDetailsController(university.buildings.getBuildingByIndex(command - offset));
        } catch (UniversityWarning e) {
            return this;
        }
    }

}
